package com.gopay.checkorder.service.task;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BcdlOrderSendBankService;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.BcdlMessage;
import com.gopay.common.domain.bank.BcdlResult;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.SendMail;
import com.gopay.common.util.spring.SpringContextUtil;

/**
 * 网联对账文件下载
 *
 * @author lynn
 * @data
 */
public class NuccDownloadCheckFileTaskImpl implements Task {

	private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");
	@Resource(name = "nuccDownloadConfig")
	private Map<String, String> nuccDownloadConfig;
	@Resource(name = "commonQueryDAO")
	private CommonQueryDAO commonQueryDAO;
	
	@Override
	public void doTask() {
		logger.info("NuccDownloadCheckFileTaskImpl: 定时任务start ");
		try {
			if ("off".equals(nuccDownloadConfig.get("mailSwitch"))) {
				logger.error("NuccDownloadCheckFileTaskImpl: 不进行sftp操作直接返回!");
				return;
			}
			String beanName = BankConstants.BANK_LOGO_NUCCPAY + "-BCDL";
			BcdlOrderSendBankService sendBankService = (BcdlOrderSendBankService) SpringContextUtil.getBean(beanName);

			BcdlMessage req = new BcdlMessage();
			req.setBank(BankConstants.BANK_LOGO_NUCCPAY);
			BcdlResult result = sendBankService.queryAcctDetail(req);
			Map map = new HashMap<String, Object>();
			map = (Map) result.getDefaultModel();
			List names = (List) map.get("names");
			String localPath = (String) map.get("localPath");
			List sendFile = new ArrayList();

			// 若对账文件全部为空，则邮件内容标明
			if (names.size() < 1) {
				logger.error("NuccDownloadCheckFileTaskImpl: 网联交易对账文件为null或本地已成功下载!");
				return;
			} else {
				String subject = "网联交易对账文件";
				String messageText = "附件为网联交易对账文件, 请查收!";
				String[] cc = nuccDownloadConfig.get("sendmail.cc").split(","); // 获取多个抄送人
				List<String> ccList = Arrays.asList(cc);

				// messageText = batNo + ": 网联交易对账文件见附件! " + decryptFileName +
				// "为: 汇总对账文件, 其他为交易明细对账文件";
				for (int i = 0; i < names.size(); i++) {
					sendFile.add(localPath + (String) names.get(i));
				}

				try {
					SendMail.sendMessage(nuccDownloadConfig.get("sendmail.host"), nuccDownloadConfig.get("sendmail.sender"), nuccDownloadConfig.get("sendmail.username"),
							nuccDownloadConfig.get("sendmail.password"), nuccDownloadConfig.get("sendmail.receiver"), subject, messageText, "text/html;charset=gb2312", ccList,
							sendFile, names);

				} catch (MessagingException e) {
					logger.error("NuccDownloadCheckFileTaskImpl sendMail error: ", e);
				}

			}
		} catch (Exception e) {
			logger.error("NuccDownloadCheckFileTaskImpl error: ", e);
		}
	}
}
